#!/bin/bash

# 生产服务器最终修复脚本
# 解决后端服务启动和Nginx配置问题

echo "=== 生产服务器修复脚本 ==="
echo "开始时间: $(date)"

# 步骤1: 停止可能运行的服务
echo "\n1. 停止现有服务..."
pkill -f "node.*start-server.js" || echo "没有运行的Node.js服务"

# 步骤2: 进入正确的后端目录并启动服务
echo "\n2. 启动后端服务..."
cd /opt/cumrbull/backend/

# 检查目录是否存在
if [ ! -d "/opt/cumrbull/backend" ]; then
    echo "错误: 后端目录 /opt/cumrbull/backend 不存在"
    exit 1
fi

# 检查start-server.js文件
if [ ! -f "start-server.js" ]; then
    echo "错误: start-server.js 文件不存在"
    exit 1
fi

# 安装依赖（如果需要）
if [ -f "package.json" ]; then
    echo "安装Node.js依赖..."
    npm install
fi

# 启动后端服务
echo "启动Node.js后端服务..."
nohup node start-server.js > /var/log/backend.log 2>&1 &
BACKEND_PID=$!
echo "后端服务已启动，PID: $BACKEND_PID"

# 等待服务启动
sleep 5

# 检查服务是否正常运行
if ps -p $BACKEND_PID > /dev/null; then
    echo "✓ 后端服务运行正常"
else
    echo "✗ 后端服务启动失败，查看日志:"
    tail -20 /var/log/backend.log
    exit 1
fi

# 步骤3: 创建完整的Nginx配置
echo "\n3. 创建Nginx配置文件..."

# 删除空的配置文件
rm -f /etc/nginx/conf.d/cu-mr-bull.conf

# 创建完整的Nginx配置
cat > /etc/nginx/conf.d/cu-mr-bull.conf << 'EOF'
# Cu Mr Bull 生产环境 Nginx 配置
# 上游服务器定义
upstream cu_mr_bull_api {
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

# 速率限制
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=admin_limit:10m rate=5r/s;

# API服务器配置 (api.cumrbull.com.sg)
server {
    listen 80;
    server_name api.cumrbull.com.sg;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name api.cumrbull.com.sg;

    # SSL配置
    ssl_certificate /etc/ssl/certs/cumrbull.crt;
    ssl_certificate_key /etc/ssl/private/cumrbull.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 安全头
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 日志
    access_log /var/log/nginx/api.cumrbull.access.log;
    error_log /var/log/nginx/api.cumrbull.error.log;

    # 健康检查端点
    location /health {
        proxy_pass http://cu_mr_bull_api/health;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 10s;
    }

    # API路由
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        
        proxy_pass http://cu_mr_bull_api/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }

    # 根路径重定向到健康检查
    location = / {
        return 302 /health;
    }
}

# 管理后台服务器配置 (admin.cumrbull.com.sg)
server {
    listen 80;
    server_name admin.cumrbull.com.sg;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name admin.cumrbull.com.sg;

    # SSL配置
    ssl_certificate /etc/ssl/certs/cumrbull.crt;
    ssl_certificate_key /etc/ssl/private/cumrbull.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 安全头
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # 日志
    access_log /var/log/nginx/admin.cumrbull.access.log;
    error_log /var/log/nginx/admin.cumrbull.error.log;

    # 管理后台API路由
    location /api/ {
        limit_req zone=admin_limit burst=10 nodelay;
        
        proxy_pass http://cu_mr_bull_api/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }

    # 静态文件服务（如果有管理界面）
    location / {
        # 如果有静态管理界面，指向静态文件目录
        # root /var/www/admin;
        # try_files $uri $uri/ /index.html;
        
        # 临时重定向到API健康检查
        return 302 /api/health;
    }
}
EOF

echo "✓ Nginx配置文件已创建"

# 步骤4: 测试和重载Nginx
echo "\n4. 测试Nginx配置..."
nginx -t
if [ $? -eq 0 ]; then
    echo "✓ Nginx配置语法正确"
    systemctl reload nginx
    echo "✓ Nginx已重新加载"
else
    echo "✗ Nginx配置语法错误"
    exit 1
fi

# 步骤5: 验证部署
echo "\n5. 验证部署状态..."

# 检查后端服务
echo "检查后端服务:"
if netstat -tlnp | grep :3000; then
    echo "✓ 后端服务运行在端口3000"
else
    echo "✗ 后端服务未在端口3000运行"
fi

# 检查Nginx状态
echo "\n检查Nginx状态:"
systemctl status nginx --no-pager -l

# 测试API端点
echo "\n测试API端点:"
echo "测试健康检查:"
curl -k -s -o /dev/null -w "HTTP状态码: %{http_code}\n" https://api.cumrbull.com.sg/health || echo "连接失败"

echo "\n测试管理后台API:"
curl -k -s -o /dev/null -w "HTTP状态码: %{http_code}\n" https://admin.cumrbull.com.sg/api/health || echo "连接失败"

echo "\n=== 修复脚本完成 ==="
echo "完成时间: $(date)"
echo "\n请检查上述输出，确保所有服务正常运行。"
echo "如有问题，请查看日志文件:"
echo "- 后端日志: /var/log/backend.log"
echo "- Nginx访问日志: /var/log/nginx/*.access.log"
echo "- Nginx错误日志: /var/log/nginx/*.error.log"